package com.wish.service.impl;

import com.wish.entity.SysUserToken;
import com.wish.mapper.SysUserMapper;
import com.wish.mapper.SysUserTokenMapper;
import com.wish.service.ISysUserTokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.util.TokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 系统用户Token 服务实现类
 * </p>
 *
 * @author 五组
 * @since 2021-03-22
 */
@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserToken> implements ISysUserTokenService {

    @Autowired
    private SysUserTokenMapper sysUserTokenMapper;

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Override
    public SysUserToken createToken(Long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        SysUserToken tokenEntity = sysUserTokenMapper.selectById(userId);
        if(tokenEntity == null){
            tokenEntity = new SysUserToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            sysUserTokenMapper.insert(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            sysUserTokenMapper.updateById(tokenEntity);
        }

        //R r = R.ok().put("token", token).put("expire", EXPIRE);

        return tokenEntity;
    }
}
